<script setup>
	import {onLoad} from '@dcloudio/uni-app'
	import {computed, ref} from 'vue'
	import taskApi from '@/apis/task'
	
	// 定义原定时间
	const planDepartureTime = ref('')
	// 定义运输任务Id
	const transportTaskId = ref('')
	
	// 定义延迟时间
	const delayTime = ref('')
	// 定义延迟时间不超过2小时
	const delayTimeValid = computed(()=>{
		const start = new Date(planDepartureTime.value)
		const end = new Date(delayTime.value)
		return end - start > 0 && end - start < 7200 * 1000
	})
	
	// 定义延迟原因
	const delayReason = ref('')
	// 定义延迟原因字数
	const wordsCount = computed(()=>{
		return delayReason.value.length
	})
	// 定义字数不超过50个字
	const delayReasonvalid = computed(()=>{
		return wordsCount.value <= 50 && wordsCount.value > 0
	})
	
	// 是否允许提交表单
	const enableSubmit = computed(()=>{
		return !delayTimeValid.value || !delayReasonvalid.value
	})
	
	// 渲染
	onLoad((params)=>{
		planDepartureTime.value = params.planDepartureTime
		transportTaskId.value = params.transportTaskId
	})
	
	// 处理 - 延迟时间选择
	function onPickerChange(e) {
		const [date] = planDepartureTime.value.split(' ')
		delayTime.value = `${date} ${e.detail.value}`
	}
	// 处理 - 延迟表单提交
	async function onFormSubmit() {
		const formData = {
			id:transportTaskId.value,
			delayReason:delayReason.value,
			delayTime:delayTime.value
		}
		const {code} = await taskApi.delay(formData)
		if(code!==200) return uni.utils.toast('延迟提货申请失败！')
		uni.reLaunch({
			url:'/pages/task/index'
		})
	}
	
</script>

<template>
  <view class="page-container">
    <uni-list :border="false">
      <uni-list-item title="原定时间 " showArrow :right-text="planDepartureTime" />
      <uni-list-item title="延迟时间" showArrow>
        <template v-slot:footer>
          <picker @change="onPickerChange" class="time-picker" mode="time">
            <text v-if="!delayTime">不可超过2个小时</text>
            <text :class="{error:!delayTimeValid}" v-else>{{delayTime}}:00</text>
          </picker>
        </template>
      </uni-list-item>
      <uni-list-item direction="column">
        <template v-slot:body>
          <view class="textarea-wrapper">
            <textarea
			  v-model="delayReason"
              class="textarea"
              placeholder-style="color: #818181"
              placeholder="请输入延迟提货原因"
            ></textarea>
            <text :class="{error:wordsCount>50}" class="words-count">{{wordsCount}}/50</text>
          </view>
        </template>
      </uni-list-item>
      <uni-list-item :border="false">
        <template v-slot:body>
          <button :disabled="enableSubmit" class="button" @click="onFormSubmit">提交</button>
        </template>
      </uni-list-item>
    </uni-list>
  </view>
</template>

<style lang="scss" scoped>
  @import './index.scss';
</style>
